<?php

namespace App\Http\Controllers\Wx;

use App\CodeResponse;
use App\Services\User\AddressServices;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AddressController extends WxController
{
    /**
     * 获取用户地址列表
     * @return JsonResponse
     */
    public function list()
    {
        $list = AddressServices::getInstance()->getAddressListByUserId($this->user()->id);
        return $this->successPaginate($list);
    }
    // 获取收货地址详情
    public function detail(Request $request)
    {
        $id = (int)$request->input('id', 0);
        $detail = AddressServices::getInstance()->getAddress($this->user()->id, $id);
        if (empty($detail)) {
            return $this->fail(CodeResponse::PARAM_VALUE_ILLEGAL);
        }
//        $example = function () use ($detail) {
//            $detail = $detail->toArray();
//            $item = [];
//            foreach ($detail as $key => $value) {
//                $key = lcfirst(Str::studly($key));
//                $item[$key] = $value;
//            }
//            return $item;
//        };
        return $this->success($detail);
    }

    // 保存收货地址
    public function save(Request $request)
    {
        $id = $request->input('id', 0);
        $address = [
            'name'           => $request->input('name'),
            'tel'            => $request->input('tel'),
            'province'       => $request->input('province'),
            'city'           => $request->input('city'),
            'county'         => $request->input('county'),
            'area_code'      => $request->input('areaCode'),
            'address_detail' => $request->input('addressDetail'),
            'is_default'     => $request->input('isDefault'),
        ];
        AddressServices::getInstance()->checkAddressParam($address);
        $userId = $this->user()->id;
        if (empty($id)) {
            // 编辑
            AddressServices::getInstance()->addAddress($userId, $address);
        } else {
            // 编辑
            AddressServices::getInstance()->editAddress($userId, $id, $address);
        }

        return $this->success();
    }

    // 删除地址
    public function delete(Request $request)
    {
        $id = $request->input('id', 0);
        if (empty($id) && !is_numeric($id)) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        AddressServices::getInstance()->delete($this->user()->id, $id);
        return $this->success();
    }
}